/*************************************************
  * 描述：提供标准 model-view 接口，支持按节点绑定数据、插入/删除/更新、节点编辑回调。
  *
  * File：cxitreemodel.h
  * Author：chenyujin@mozihealthcare.cn
  * Date：2025/9/28
  * Update：
  * ************************************************/
#ifndef COREXI_COMMON_PC_CXITREEMODEL_H
#define COREXI_COMMON_PC_CXITREEMODEL_H

#include <QAbstractItemModel>
#include <controls/tree/cxitreenode.h>

class CxiTreeModel : public QAbstractItemModel
{
	Q_OBJECT
public:
	explicit CxiTreeModel(QObject* parent = nullptr);
	~CxiTreeModel();

	using EditValidator = std::function<bool(const QModelIndex&, const QString& newValue)>;

	// model interface
	QModelIndex index(int row, int column = 0, const QModelIndex& parent = QModelIndex()) const override;
	QModelIndex parent(const QModelIndex& child) const override;
	int rowCount(const QModelIndex& parent = QModelIndex()) const override;
	int columnCount(const QModelIndex& parent = QModelIndex()) const override
	{
		Q_UNUSED(parent);
		return 1;
	}

	QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
	bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
	Qt::ItemFlags flags(const QModelIndex& index) const override;

	bool insertNode(const QModelIndex& parent, int position, CxiTreeNode::Ptr node);
	bool removeNode(const QModelIndex& index);

	// 树model根节点
	CxiTreeNode::Ptr rootNode() const;

	// set validator callback (can block/transform edits)
	void setEditValidator(EditValidator v);

signals:
	void nodeEdited(const QModelIndex& index, const QString& newValue);
	void nodeCheckStateChanged(const QModelIndex& index, Qt::CheckState state);

private:
	CxiTreeNode::Ptr nodeFromIndex(const QModelIndex& index) const;
	QModelIndex indexFromNode(CxiTreeNode::Ptr node) const;

	CxiTreeNode::Ptr m_root;
	EditValidator m_validator;
};
#endif//COREXI_COMMON_PC_CXITREEMODEL_H
